package com.zitronella.course.osseventmanager.mvc;

import com.zitronella.course.osseventmanager.domain.Position;
import com.zitronella.course.osseventmanager.domain.EventUser;
import com.zitronella.course.osseventmanager.domain.Event;
import com.zitronella.course.osseventmanager.service.PositionService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@SessionAttributes(types = Position.class)
public class AddPositionController {

    private PositionService positionService;

    @Autowired
    public void setPositionService(PositionService positionService) {
        this.positionService = positionService;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields(new String[] {"id"});
    }

    @RequestMapping(value = "/position/new", method = RequestMethod.GET)
    public String setupForm(Model model) {
        model.addAttribute("position", new Position());
        return "position";
    }

    @RequestMapping(value = "/position/new", method = RequestMethod.POST)
    public String saveItem(@ModelAttribute Position position, BindingResult result, HttpSession session) {
        if (StringUtils.isBlank(position.getName()))
            result.rejectValue("name", "required", "Required");

            positionService.addPosition(getEventUser(session), position);
            return "redirect:/";
    }

     private Event getEventUser(HttpSession session) {
        return (Event) session.getAttribute("event");
    }

}



